package com.gitee.wsl.compose.ui.textfield.filter

import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.TextFieldValue
import com.gitee.wsl.compose.ui.base.TextField
import com.gitee.wsl.ext.base.ifValue
import com.gitee.wsl.transform.validator.string.StringValidator

typealias FiledFilterFun = (TextFieldValue) -> Unit

open class BaseFieldFilter {
    private var _inputValue = mutableStateOf(TextFieldValue())

    val inputValue get() = _inputValue.value

    protected open fun onFilter(inputTextFieldValue: TextFieldValue, lastTextFieldValue: TextFieldValue): TextFieldValue {
        return TextFieldValue()
    }

    protected open fun computePos(): Int {
        // TODO
        return 0
    }

    protected fun getNewTextRange(
        lastTextFiled: TextFieldValue,
        inputTextFieldValue: TextFieldValue
    ): TextRange? {
        if (lastTextFiled.text == inputTextFieldValue.text) return null // 内容没改变，只是光标变动

        return TextRange(lastTextFiled.selection.start, inputTextFieldValue.selection.end)
    }

    protected fun getNewText(
        lastTextFiled: TextFieldValue,
        inputTextFieldValue: TextFieldValue
    ): TextRange? {
        if (lastTextFiled.text == inputTextFieldValue.text) return null // 内容没改变，只是光标变动

        return TextRange(lastTextFiled.selection.start, inputTextFieldValue.selection.end)
    }


    fun onValueChange(): FiledFilterFun {
        return {
            _inputValue.value = onFilter(it, _inputValue.value)
        }
    }

    fun setValue(newValue: String) {
        _inputValue.value = TextFieldValue(
            text = newValue,
            selection = TextRange(newValue.length)
        )
    }
}

class StringMatchFilter(val matchFun:StringValidator): BaseFieldFilter() {
    override fun onFilter(
        inputTextFieldValue: TextFieldValue,
        lastTextFieldValue: TextFieldValue,
    ): TextFieldValue {
        return matchFun(inputTextFieldValue.text).ifValue(inputTextFieldValue,lastTextFieldValue)
    }
}

@Composable
fun TextField.Filter.validator(matchFun: StringValidator)= remember {
    StringMatchFilter(matchFun)
}